<template>
  <section>
    <!--#region 搜索条-->

    <xt-search @search="handleSearch" v-if="searchFlag" :searchFlag="getOperation('list')">
      <el-select v-model="filters.appId" :placeholder="$t('menu.app')" size="small" class="search-box__input" @change="handleSearch">
        <el-option
          v-for="item in appList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
        <el-input v-model="filters.code" :placeholder="$t('menu.code')" size="small" class="search-box__input" clearable @keyup.enter.native="handleSearch"></el-input>
        <el-input v-model="filters.name" :placeholder="$t('menu.name')" size="small" class="search-box__input" clearable @keyup.enter.native="handleSearch"></el-input>
        <template slot="actions">
          <el-button size="small" class="search-box__button" type="primary" icon="plus" @click="handleAdd" v-if="getOperation('insert')">{{$t('add')}}</el-button>
          <el-dropdown @command="handleDropDown" v-if="appList && appList.length>0 && getOperation('copy')">
            <el-button type="primary" size="small" style="margin-left:10%">
              {{$t('menu.copyMenu')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <template v-for="(item, index) in appList">
                <el-dropdown-item :key="index" :disabled="item.id===filters.appId" :command="item">
                  {{item.name}}
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </xt-search>

    <!--#endregion-->

    <!--#region 页面主要列表-->

    <!--列表-->

    <div class="search-button">
      <el-button class="button" icon="el-icon-search" circle size="small" @click="handleSearchFlag"></el-button>
    </div>
    <el-table :data="menuList" highlight-current-row v-loading="loading.listLoading" style="width: 100%;" stripe border @expand-change="expandHandle">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <menu-tag :data="scope.row" @handleAdd="handleAdd" @handleEdit="handleEdit" @handleDel="deleteData"></menu-tag>
        </template>
      </el-table-column>
      <el-table-column align="left" header-align="center" type="index" width="56" :label="$t('index')">
        <template slot-scope="scope">
          {{(pageInfo.pageIndex-1)*pageInfo.pageSize+scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column
        prop="appName"
        align="center"
        :label="$t('menu.app')" minWidth="120"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span >{{scope.row.appName}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="code"
        align="center"
        :label="$t('menu.code')" minWidth="120"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span >{{scope.row.code}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        align="center"
        :label="$t('menu.name')" minWidth="120"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="icon"
        align="center"
        :label="$t('menu.icon')" width="90">
        <template slot-scope="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column
        prop="url"
        align="center"
        :label="$t('menu.url')" minWidth="120"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span >{{scope.row.url}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="module"
        align="center"
        :label="$t('menu.module')" width="100"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span >{{scope.row.modules.join(",")}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        align="center"
        :label="$t('menu.sort')" width="68">
      </el-table-column>
      <el-table-column
        prop="displayFlag"
        align="center"
        :label="$t('menu.displayFlag')" width="90">
        <template slot-scope="scope">
          {{scope.row.displayFlag ? "√" : "×"}}
        </template>
      </el-table-column>
      <el-table-column align="left" header-align="center" :label="$t('operation')" :width="operationWidth('update|delete')" v-if="getOperation('update|delete')">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handleEdit(scope.row)" v-if="getOperation('update')">{{$t('modify')}}</el-button>
          <el-button size="mini" type="danger" @click="deleteData(scope.row)" v-if="getOperation('delete')">{{$t('delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--#endregion-->

    <!--#region 工具条-->

    <!--工具条-->

    <el-row>
      <el-col :span="24" class="toolbar">
        <el-pagination
          style="float:right;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageInfo.pageSize"
          layout="sizes, prev, pager, next"
          :total="pageInfo.count">
        </el-pagination>
      </el-col>
    </el-row>

    <!--#endregion-->

    <!--#region 新增修改页面-->

    <!--新增界面-->

    <el-dialog width="95%" top="20px" :title="formData.id===0?$t('add'):$t('modify')" :visible.sync="dialog.formDataVisible" :close-on-click-modal="false" :modal-append-to-body="false">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formData">
        <el-form-item :label="$t('menu.app')" prop="appId" v-show="formData.parentId===0">
          <el-select v-model="formData.appId" :placeholder="$t('menu.validateApp')">
            <el-option
              v-for="item in appList"
              :label="item.name"
              :value="item.id" :key="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('menu.code')" prop="code">
          <el-input :placeholder="$t('menu.validateCode')" v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item :label="$t('menu.name')" prop="name">
          <el-input :placeholder="$t('menu.validateName')" v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('menu.url')" prop="url">
          <el-input :placeholder="$t('menu.validateUrl')" v-model="formData.url"></el-input>
        </el-form-item>
        <el-form-item :label="$t('menu.type')" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio :label="1">{{$t('menu.menu')}}</el-radio>
            <el-radio :label="2">{{$t('menu.page')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('menu.module')" prop="modules">
          <el-select v-model="formData.modules" :placeholder="$t('menu.validateModule')" style="width: 100%;" multiple>
            <el-option
              v-for="item in moduleList"
              :label="item.key"
              :value="item.value" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('menu.sort')" prop="sort">
          <el-input-number v-model="formData.sort" :placeholder="$t('menu.validateSort')" :min="0" :controls="false" :max="9999"
                           style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('menu.icon')" prop="icon">
          <span style="color: #1c8de0; font-size: 1.5rem"><i :class="formData.icon"></i></span>
          <el-button type="success" size="mini" @click.native="dialog.iconVisible = true">{{$t('menu.selectIcon')}}</el-button>
          <span style="padding-left: 1rem">{{$t('menu.displayFlag')}}</span>
          <el-checkbox v-model="formData.displayFlag"></el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCancel">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click.native="submitData" :loading="loading.addLoading">{{$t('submit')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('menu.selectIcon')" :visible.sync="dialog.iconVisible" :modal-append-to-body="false" :close-on-click-modal="false" width="80%">
      <div class="iconbox">
        <div class="item" v-for="(item,index) in allIcon" @click="handleIcon(item)" :key="index">
          <i :class="item"></i>
        </div>
      </div>
    </el-dialog>
    <!--#endregion-->

  </section>
</template>

<script>

/*#region 导入函数*/
import {AppAPI, getAllIcons} from "../../modules";
import PagePlugIn from "../../mixins/page-plug-in";
import {MenuAPI, DictAPI} from "../../modules";
import {DictType} from "../../modules/enums/dicts";
import MenuTag from "./src/menuTag";
import lodashArray from "lodash/array";

/*#endregion*/

export default {
  name: "Menu",
  methods: {

    /*#region 自定义函数(组件change事件等)*/
    expandHandle(row, expanded) {
      return new Promise(function (resolve) {
        if (expanded) {
          row.loading = true;
          MenuAPI.listMenu({pageIndex: 1, pageSize: 999999, parentId: row.id}).then(({list}) => {
            row.loading = false;
            list.map(function (element) {
              element.modules = element.module ? element.module.split(",") : "" || [];
              element.modules = lodashArray.uniq(element.modules);
              lodashArray.remove(element.modules, (n) => n === "" || n === " ");
              element.childs = [];
            });
            list.sort(function (a, b) {
              return a.sort - b.sort;
            });
            row.children = list;
            resolve();
          });

          /* } else {
               resolve()
           }*/
        }
      });
    },

    /*#endregion*/

    /*#region 数据提交事件*/

    //提交事件

    submitData() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.formData));
          params.module = params.modules.join(",");
          if (params.id === 0) {
            this.loading.addLoading = true;
            MenuAPI.insertMenu(params).then(({data}) => {
              this.loading.addLoading = false;
              if (data.code === 1) {
                this.$refs.formData.resetFields();
                this.getMainList();
                this.dialog.formDataVisible = false;
              } else {
                this.$message({
                  message: data.msg || "新增失败",
                  type: "error"
                });
              }
            });
        } else {
          this.loading.addLoading = true;
          MenuAPI.updateMenu(params).then(({data}) => {
            this.loading.addLoading = false;
            if (data.code === 1) {
              this.$refs.formData.resetFields();
              this.getMainList();
              this.dialog.formDataVisible = false;
            } else {
              this.$message({
                message: data.msg || "新增失败",
                type: "error"
              });
            }
           
          });
          }
        }
      });
    },

    //删除

    deleteData(row, parent) {
      this.$confirm(this.$t('deleteConfirm'), this.$t('tips'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: "warning"
      }).then(() => {
        MenuAPI.deleteMenu({id: row.id}).then(({data}) => {
          if (data.code === 1) {
            if (row.parentId !== 0) {
              this.getChildMenuList(row, parent);
              return true;
            }
            this.getMainList();
          }
        });
      });
    },


    /*#endregion*/

    /*#region 操作函数(handle)*/

    //修改

    handleEdit(row, data) {
      this.menuTagData = data || {};
      this.$refs.formData && this.$refs.formData.resetFields();
      this.formData = JSON.parse(JSON.stringify(row));
      this.dialog.formDataVisible = true;
    },
    handleCancel() {
      this.dialog.formDataVisible = false;
    },
    handleAdd(row) {
      this.$refs.formData && this.$refs.formData.resetFields();
      this.formData = {...MenuAPI.init(), appId: row.appId || null, parentId: row.id || 0, type: 1, displayFlag: true, modules: []};
      this.dialog.formDataVisible = true;
    },
    handleIcon(icon) {
      this.formData.icon = icon;
      this.dialog.iconVisible = false;
    },
    handleDropDown(item) {
      this.$confirm(this.$t('menu.comfirmCopy'), this.$t('tips'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        const params = {fromAppId: this.filters.appId, toAppId: item.id};
        MenuAPI.updateCopy(params);
      });
    },


    /*#endregion*/

    /*#region 获取数据*/

    getChildMenuList(row, parent) {
      const params = {
        parentId: row.parentId || 0,
        orderBy: "sort asc",
        pageIndex: 1,
        pageSize: 9999
      };
      MenuAPI.listMenu(params).then(({data, list}) => {
        list.map((element) => {
          element.modules = element.module ? element.module.split(",") : "" || [];
          element.modules = lodashArray.uniq(element.modules);
          lodashArray.remove(element.modules, (n) => n === "" || n === " ");
          const appItem = this.appList.find((i) => i.id === element.appId);
          if (appItem) {
            element.appName = appItem.name || "";
          }
        });
        parent.children = list;
      });
    },
    getMainList() {
      const params = {
        ...this.getParams(),
        appId: this.filters.appId,
        parentId: 0,
        orderBy: "sort asc"
      };
      this.loading.listLoading = true;
      MenuAPI.listMenu(params).then(({data, list}) => {
         this.loading.listLoading = false;
        list.map((element) => {
          element.modules = element.module ? element.module.split(",") : "" || [];
          element.modules = lodashArray.uniq(element.modules);
          lodashArray.remove(element.modules, (n) => n === "" || n === " ");
          const appItem = this.appList.find((i) => i.id === element.appId);
          if (appItem) {
            element.appName = appItem.name || "";
          }
        });
        this.menuList = list;
        this.pageInfo.pageIndex = data.data ? data.data.currentPage : 1;
        this.pageInfo.count = data.data ? data.data.count : 0;
      });
    },
    getModuleList() {
      DictAPI.listDict({
          type: DictType.module,
          pageIndex: 1,
          pageSize: 2147483647,
          orderBy: "`Key` Asc"
        }).then(({res, list}) => {
          this.moduleList = list || [];
        });
    }

    /*#endregion*/

  },

  /*#region 生命周期函数(created、mount、等)*/

  created() {
    this.getModuleList();
    this.loading.listLoading = true;
    AppAPI.listApp({pageIndex: 1, pageSize: 9999}).then(({list}) => {
      this.appList = list;
      if (list.length > 0) {
        this.filters.appId = list[0].id;
      }
      this.getMainList();
    });
  },

  /*#endregion*/

  /*#region 注册绑定数据*/

  components: {MenuTag},
  data() {
    return {
      filters: {...MenuAPI.init(), appId: ""},
      formData: MenuAPI.init(),
      formRules: {
        url: [
          {required: true, message: this.$t('menu.validateUrl'), trigger: "blur"}
        ],
        code: [
          {required: true, message: this.$t('menu.validateCode'), trigger: "blur"},
          {min: 1, max: 200, message: this.$t('menu.validateLength200'), trigger: "blur"}
        ],
        name: [
          {required: true, message: this.$t('menu.validateName'), trigger: "blur"},
          {min: 1, max: 200, message: this.$t('menu.validateLength200'), trigger: "blur"}
        ],
        appId: [
          {required: true, message: this.$t('menu.validateApp'), trigger: "change"}
        ],
        icon: [
          {required: true, message: this.$t('menu.validateIcon'), trigger: "change"}
        ],
        sort: [{required: false, type: "number", message: "", trigger: "change"}],
        type: [{required: true, message: this.$t('menu.validateType'), trigger: "change"}],
         modules: [{required: true, message: this.$t('menu.validateModule'), trigger: "change"}]
      },
      dialog: { formDataVisible: false, iconVisible: false },
      loading: { addLoading: false, listLoading: false },
      menuList: [],
      appList: [],
      allIcon: getAllIcons(),
      menuTagData: {},
      moduleList: []
    };
  },
  mixins: [PagePlugIn]

  /*#endregion */

};
</script>

<style scoped lang="scss">
  @import "../../assets/styles/scss/views/menu/menu";
</style>
